<?php
    include_once 'db.php';
    session_start();
    if(!$_SESSION["passed"]) return false;

    $actionType = $_POST["atype"];
    $param = $_POST["param"];

    // $param = json_decode($queryParam, true);

    function get_occujpation_num($query_where, $query_param) {
        $query_str = "select count(*) as count from d_occupation where 1 = 1 ".$query_where;
        // echo $query_str;
        $count = mysql_fetch_assoc(dbOperate($query_str, $query_param));
        $count = $count['count'];
        return $count ? $count : 0;
    }

    function insert_occupation($param) {

    };

    function delete_occupation($param) {

    };

    function update_occupation($param) {

    }

    function query_occupation($param) {
        $o_code_parent = $param['o_code_parent'];
        $o_desc = $param['o_desc'];
        $page = $param['page'];
        $page_size = $param['pageSize'];
        $sortName = $param['sortName'] ? $param['sortName'] : 'last_modify';
        $sortOrder = $param['sortOrder'] ? $param['sortOrder'] : 'desc';

        $query_param = array();
        $clip = "";
        if(!!$o_desc) {
            $clip = $clip." and instr('o_desc', '%s') ";
            array_push($query_param, $o_desc);
        }
        if(!!$o_code_parent) {
            $clip = $clip." and o_code_parent, %q) ";
            array_push($query_param, $o_code_parent);
        }
        $count = get_occujpation_num($clip, $query_param);

        $pages = intval($count / $page_size);
        $pages = $count % $page_size > 0 ? $pages + 1 : $pages;

        array_push($query_param, $page - 1);
        array_push($query_param, $page_size);

        $query_str = "select * from d_occupation where 1 = 1 ".$clip." order by ".$sortName." ".$sortOrder." limit %i, %i";
        // echo $query_str;
        $result = dbOperate($query_str, $query_param);

        $arr = array();
        while($row = mysql_fetch_assoc($result))
        {
          array_push($arr, $row);
        }
        $rows = array("Rows"=>$arr, "curPage"=>$page, "pages"=>$pages);

        return json_encode($rows);
    };


    $result = 0;
    switch($actionType) {
        case "c":
            $result = insert_occupation($param);
            break;
        case "r":
            $result = query_occupation($param);
            break;
        case "u":
            $result = update_occupation($param);
            break;
        case "d":
            $result = delete_occupation($param);
            break;
        default:
            $result = 0;
            break;
    }
    echo $result;
?>